package com.mlog.njyjy.ndop.monitor.collector.task;

import com.mlog.njyjy.ndop.monitor.collector.dao.TaskRepository;
import com.mlog.njyjy.ndop.monitor.collector.factory.ScanRouteFactory;
import com.mlog.njyjy.ndop.monitor.collector.route.ScanRoute;
import com.mlog.njyjy.ndop.monitor.common.domain.CollectWay;
import com.mlog.njyjy.ndop.monitor.common.domain.Task;
import com.mlog.njyjy.ndop.monitor.common.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.CamelContext;

/**
 * 扫描产品信息线程
 *
 * @author zyz
 * @version v1.0, 2020/07/28
 */
@Slf4j
public class ScanPdtRunnable implements Runnable {

    private CamelContext context;

    private Task task;

    private TaskRepository taskRepository;

    private ScanRouteFactory scanRouteFactory;

    public ScanPdtRunnable(CamelContext camelContext, Task task, TaskRepository taskRepository, ScanRouteFactory scanRouteFactory) {
        this.context = camelContext;
        this.task = task;
        this.taskRepository = taskRepository;
        this.scanRouteFactory = scanRouteFactory;
    }

    private void stop(int taskId) {
        try {
            context.stopRoute("taskId-" + taskId);
            context.removeRoute("taskId-" + taskId);
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());

        }
    }

    @Override
    public void run() {
        log.info("start scan product [{}]", task.getProductName());
        try {
            CollectWay collectWay = taskRepository.findWays(task.getCollectWayId());
            ScanRoute scanRoute = scanRouteFactory.get(collectWay.getMode());
            context.addRoutes(scanRoute.creatRoute(task.getId()));
            log.info("产品 {} scanning...", task.getProductName().concat(".").concat(task.getPdtFileExt()));
            Thread.sleep(DateTimeUtil.toTimestamp(task.getEndProcAt()) - DateTimeUtil.toTimeStamp());
            stop(task.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
